#include "BulletSystem.h"
#include "..\..\Constants.h"

// -------------------------------------------------
// 
// -------------------------------------------------
BulletSystem::~BulletSystem() {
	clear();
}

void BulletSystem::clear() {
	for ( size_t i = 0; i < m_Bullets.size();++i ) {
		Bullet* b = &m_Bullets[i];		
		m_CD.remove(b->handle);
		delete b->sprite;
	}
	m_Bullets.clear();
}

void BulletSystem::setFireMode(FireMode fireMode) {
	m_FireMode = fireMode;
	// FIXME: set timer!
	m_DoubleTimer = 0.0f;
	m_TripleTimer = 0.0f;
}

void BulletSystem::start(const ds::Vec2& position) {
	if ( m_FireMode == FM_SINGLE ) {
		start(position,0.0f,BULLET_COLOR);
	}
	if ( m_FireMode == FM_DOUBLE ) {
		ds::Vec2 p = position;
		p.x -= 15.0f;
		start(p,0.0f,ds::Color(0.6f,0.0f,0.0f,1.0f));
		p.x += 30.0f;
		start(p,0.0f,ds::Color(0.6f,0.0f,0.0f,1.0f));
	}
	if ( m_FireMode == FM_TRIPLE ) {
		ds::Vec2 p = position;
		p.x -= 15.0f;
		start(p,0.0f,ds::Color(0.0f,0.78f,0.9f,1.0f));
		p.x += 15.0f;
		start(p,0.0f,ds::Color(0.0f,0.78f,0.9f,1.0f));
		p.x += 15.0f;
		start(p,0.0f,ds::Color(0.0f,0.78f,0.9f,1.0f));
	}
}

void BulletSystem::start(const ds::Vec2& position,float angle,const ds::Color& color) {
	Bullet b;
	b.sprite = new ds::Sprite(position,BULLET_RECT);
	b.sprite->scale = BULLET_SIZE;
	b.sprite->color = color;
	b.sprite->rotation = DEGTORAD(90.0f);
	b.angle = angle;
	b.velocity.x = 0.0f;
	b.velocity.y = - 1.0f * BULLET_SPEED;
	b.handle = m_CD.addCircle(ds::Vec2(0,0),ds::Vec2(24,24),12,BULLET_ID);
	m_Bullets.push_back(b);
}

void BulletSystem::update(float elapsed) {
	if ( m_FireMode == FM_DOUBLE ) {
		m_DoubleTimer += elapsed;
		if ( m_DoubleTimer > DOUBLE_BULLETS_TTL ) {
			setFireMode(FM_SINGLE);
		}
	}
	if ( m_FireMode == FM_TRIPLE ) {
		m_TripleTimer += elapsed;
		if ( m_TripleTimer > TRIPLE_BULLETS_TTL ) {
			setFireMode(FM_DOUBLE);
		}
	}
	Bullets::iterator pit = m_Bullets.begin();
	while ( pit != m_Bullets.end() ) {		
		ds::Vec2 p = pit->sprite->position;
		p += pit->velocity * elapsed;
		pit->sprite->position = p;		
		if ( p.y > -10.0f && p.y < SCR_MAX_Y && p.x > 0.0f && p.x < SCR_MAX_X ) {
			m_Sprites->addSprite(pit->sprite);
			m_CD.setPosition(pit->handle,pit->sprite->position);			
			++pit;
		}
		else {			
			m_CD.remove(pit->handle);
			delete pit->sprite;
			pit = m_Bullets.erase(pit);
		}
	}	
}

void BulletSystem::remove(uint32 index) {
	Bullets::iterator pit = m_Bullets.begin();
	while ( pit != m_Bullets.end() ) {		
		if ( pit->handle == index ) {
			m_CD.remove(pit->handle);			
			delete pit->sprite;
			pit = m_Bullets.erase(pit);
		}
		else {
			++pit;
		}
	}	
}